<template>
  <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="80%"
    :before-close="handleClose">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">

      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="生产部门" prop="cdptvid">
            <el-select class="w100p" @change="changecdptvid($event)" v-model="ruleForm.cdptvid" filterable
              placeholder="请选择生产部门">
              <el-option v-for="(item, index) in OrgDeptList" :key="index" :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item></el-col>
        <el-col :span="8">
          <el-form-item label="仓库" prop="cwarehouseid">
            <el-select class="w100p" @change="changecwarehouseid($event)" v-model="ruleForm.cwarehouseid" filterable
              placeholder="请选择仓库">
              <el-option v-for="(item, index) in StordocList" :key="index" :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出入库类型编码" prop="vtrantypecode">
            <el-input disabled v-model="ruleForm.vtrantypecode" clearable placeholder="请输入出入库类型编码" />
          </el-form-item></el-col>
        <el-col :span="8">
          <el-form-item label="业务员" prop="cbizid">
            <el-select class="w100p" @change="changecPsndocListid" v-model="ruleForm.cbizid" filterable placeholder="请选择业务员">
              <el-option v-for="(item, index) in PsndocList" :key="index" :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item></el-col>
        <!-- <el-col :span="8">
          <el-form-item label="生产库存组织" prop="cprocalbodyoid">
            <el-select class="w100p" v-model="ruleForm.cprocalbodyoid" filterable placeholder="请选择生产库存组织">
              <el-option v-for="(item, index) in OrgOrgsList" :key="index" :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item></el-col> -->
      </el-row>


      <div class="elrowBox" v-loading="loading">
        <el-row v-for="detail, index in ruleForm.detailList" :key="index">
          <div class="elrowBoxItem"></div>
          <el-col :span="6">
            <el-form-item label='物料编码' :prop="`detailList[${index}][cmaterialvid]`" :rules="rules.cmaterialvid"
              class="w100p">
              <el-select v-model="detail.cmaterialvid" filterable clearable class="w100p"
                @change="changeMaterial($event, index)">
                <el-option v-for="(item, indexson) in MaterialList" :key="indexson" :label="item.code + '/' + item.name"
                  :value="item.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label='主单位' :prop="`detailList[${index}][castunitname]`" :rules="rules.castunitname"
              class="w100p">
              <el-input disabled v-model="detail.castunitname" clearable placeholder="请输入主单位" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label='辅单位' :prop="`detailList[${index}][castunitid]`" :rules="rules.castunitid"
              class="w100p">
              <el-select @change="changeMaterialconvert($event, index)" v-model="detail.castunitid" filterable clearable
                class="w100p">
                <el-option v-for="(item, indexson) in MaterialconvertList[index]" :key="indexson"
                  :label="item.measdocname" :value="item.measdoccode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label='换算率' :prop="`detailList[${index}][vchangerate]`" :rules="rules.vchangerate">
              <el-input disabled v-model="detail.vchangerate" clearable placeholder="请输入换算率" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label='批次号' :prop="`detailList[${index}][vbatchcode]`" :rules="rules.vbatchcode">
              <el-select @change="handleChangevbatchcode($event, detail)" v-model="detail.vbatchcode" filterable
                clearable class="w100p">
                <el-option v-for="(item, indexson) in BatchcodeList[index]" :key="indexson" :label="item.vbatchcode"
                  :value="item.vbatchcode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label='养殖批次号' :prop="`detailList[${index}][vproductbatch]`" :rules="rules.vproductbatch">
              <el-select @change="handleChangevproductbatch($event, detail)" v-model="detail.vproductbatch" filterable
                clearable class="w100p">
                <el-option v-for="(item, indexson) in BatchcodeList[index]" :key="indexson" :label="item.vbatchcode"
                  :value="item.vbatchcode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label='直鱼/次鱼入库仓' :prop="`detailList[${index}][vbdef4]`" :rules="rules.vbdef4">
              <el-select @change="handleChangevbdef4($event, index)" v-model="detail.vbdef4" filterable clearable
                class="w100p">
                <el-option v-for="(item, indexson) in StordocList" :key="indexson" :label="item.name"
                  :value="item.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label='直鱼/次鱼' :prop="`detailList[${index}][vbdef5]`" :rules="rules.vbdef5">
              <el-select @change="handleChangevbdef5($event, index)" v-model="detail.vbdef5" filterable clearable
                class="w100p">
                <el-option v-for="(item, indexson) in MaterialList" :key="indexson" :label="item.code + '/' + item.name"
                  :value="item.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label='条数' :prop="`detailList[${index}][vbdef1]`" :rules="rules.vbdef1">
              <el-input v-model="detail.vbdef1" clearable placeholder="请输入条数" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label='应发辅数量' :prop="`detailList[${index}][nshouldassistnum]`"
              :rules="rules.nshouldassistnum">
              <el-input @change="handleChangenshouldassistnum($event, index)" type="number"
                v-model="detail.nshouldassistnum" clearable placeholder="请输入应发数量" />
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label='实发辅数量' :prop="`detailList[${index}][nassistnum]`" :rules="rules.nassistnum">
              <el-input @change="handleChangenassistnum(detail, index)" type="number" v-model="detail.nassistnum"
                clearable placeholder="请输入实发数量" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label='应发主数量' :prop="`detailList[${index}][nshouldnum]`" :rules="rules.nshouldnum">
              <el-input @change="handleChangenshouldnum($event, index)" type="number" v-model="detail.nshouldnum"
                clearable placeholder="请输入应发主数量" />
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label='实发主数量' :prop="`detailList[${index}][nnum]`" :rules="rules.nnum">
              <el-input @change="handleChangennum(detail, index)" type="number" v-model="detail.nnum" clearable
                placeholder="请输入实发主数量" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label='活鱼品规' :prop="`detailList[${index}][vfree1]`" :rules="rules.vfree1">
              <el-select @change="handleChangevfree1($event, index)" v-model="detail.vfree1" filterable clearable
                class="w100p">
                <el-option v-for="(item, indexson) in Defdoc2List" :key="indexson" :label="item.name"
                  :value="item.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label='均重' :prop="`detailList[${index}][vbdef2]`" :rules="rules.vbdef2">
              <el-input v-model="detail.vbdef2" clearable placeholder="请输入均重" />
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item>
              <i v-show="ruleForm.detailList.length !== 1" class="icon el-icon-remove-outline"
                @click.stop="delMaterial(index)"></i>
              <i v-show="(ruleForm.detailList.length) === index + 1" class="icon el-icon-circle-plus-outline"
                @click.stop="addMaterial()"></i>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">暂存提交</el-button>
      <el-button type="primary" @click="submitFormNc">确定提交</el-button>
    </span>
  </el-dialog>
</template>
<script>
import NcdeadRecordApi from "@/api/production-management-nc/dead-record-nc";
import ncBasicinfoApi from "@/api/nc-basic-info/index";
import ncproductionApi from "@/api/production-management-nc/index";

export default {
  components: {},
  props: {
    addEditFlag: {
      type: String,
      default: () => {
        return "add";
      },
    },
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
    title: {
      type: String,
      default: () => {
        return "操作表单";
      },
    },
    dialogVisible: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    StordocList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    OrgDeptList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    PsndocList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    OrgOrgsList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    MaterialList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    Defdoc2List: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      addEditName: "添加",
      addEditApi: "",
      ruleForm: {},
      MaterialconvertList: [], //辅单位
      BatchcodeList: [],
      rules: {
        cwarehouseid: [
          {
            required: true,
            message: "请输入",
            trigger: ["change", "blur"],
          },
        ],
        cdptvid: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        vtrantypecode: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        cprocalbodyoid: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        cbizid: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        cmaterialvid: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        measdocname: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        castunitid: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        vchangerate: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        nshouldnum: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        nshouldassistnum: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        nnum: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        nassistnum: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        vfree1: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        vbdef1: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
        vbdef2: [
          {
            required: true,
            message: "请选择",
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  computed: {},
  watch: {
    dialogVisible(v) {
      v && this.initData();
    },
  },
  mounted() { },
  methods: {
    initData() {
      if (this.addEditFlag == "add") {
        this.resetForm();
        this.addEditApi = NcdeadRecordApi.add;
        this.addEditName = "添加";
        this.ruleForm = {
          vtrantypecode: "46-01",
          detailList: [
            {
              cmaterialvid: "",
              vproductbatch: "",
              vbatchcode: "",
              nshouldassistnum: "",
              nshouldnum: "",
              nnum: "",
              nassistnum: "",
              vbdef1: "",
              vbdef2: "",
              vbdef4: "",
              vbdef5: "",
            },
          ],
        };
      } else if (this.addEditFlag == "edit") {
        this.ruleForm = { ...this.data };
        this.addEditApi = NcdeadRecordApi.edit;
        this.addEditName = "编辑";
        let detailList = this.data.detailList || []
        detailList.forEach((e, index) => {
          this.queryBatchcode(e.cmaterialvid, index)
        });
      }
    },
    async queryBatchcode(e, index) {
      let rut = this.MaterialList.find((item) => {
        return e == item.code;
      });
      let resMaterialconvert = await ncBasicinfoApi.queryMaterialconvert({
        pk_material: rut.pk_material,
      });
      let resBatchcode = await ncproductionApi.queryBatchcode({
        entity: { cmaterialvid: rut.pk_material },
        page: 1,
        size: 1000,
      });
      this.$set(this.BatchcodeList, index, resBatchcode.data.content || []);
      this.$set(this.MaterialconvertList, index, resMaterialconvert.data || []);
    },

    pushData(data) {
      this.ruleForm = { ...data };
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    //领料部门
    changecdptvid(e) {
      let rut = this.OrgDeptList.find((item) => {
        return e == item.code;
      });
      this.$set(this.ruleForm, "cdptname", rut.name);
      this.$set(this.ruleForm, "cdptid", e);
      this.$set(this.ruleForm, "cdptvid", e);
    },
    //仓库
    changecwarehouseid(e) {
      let rut = this.StordocList.find((item) => {
        return e == item.code;
      });
      this.$set(this.ruleForm, "cwarehousename", rut.name);
      this.$set(this.ruleForm, "cwarehouseid", e);
    },
    //仓库业务员
    changecPsndocListid(e) {
      let rut = this.PsndocList.find((item) => {
        return e == item.code;
      });
      this.$set(this.ruleForm, "cwhsmanagername", rut.name);
      this.$set(this.ruleForm, "cbizid", e);
    },
    //物料修改
    async changeMaterial(e, index) {
      let rut = this.MaterialList.find((item) => {
        return e == item.code;
      });
      let obj = this.ruleForm.detailList[index];
      obj.measdocname = rut.measdocname;
      obj.cmaterialvname = rut.code + '/' + rut.name;
      obj.cunitid = rut.measdoccode;
      obj.vproductbatch = null;
      obj.vchangerate = null;
      obj.castunitid = null;
      obj.vbatchcode = null;
      obj.nshouldassistnum = null;
      obj.nshouldnum = null;
      obj.nassistnum = null;
      obj.nnum = null;
      this.loading = true;
      let resMaterialconvert = await ncBasicinfoApi.queryMaterialconvert({
        pk_material: rut.pk_material,
      });
      let list = resMaterialconvert.data || [];
      let MaterialObj = list.find((item) => {
        return item.measdoccode === rut.measdoccode;
      });
      if (!MaterialObj) {
        list.push(rut);
      }
      if (list.length >= 1) {
        obj.vchangerate = list[0].measrate;
        obj.castunitid = list[0].measdoccode;
        obj.castunitname = list[0].measdocname;
      }
      let resBatchcode = await ncproductionApi.queryBatchcode({
        entity: { cmaterialvid: rut.pk_material },
        page: 1,
        size: 1000,
      });
      this.loading = false;
      this.$set(this.BatchcodeList, index, resBatchcode.data.content || []);
      this.$set(this.MaterialconvertList, index, list);
      this.$set(this.ruleForm.detailList, index, obj);
      this.changeCunitid(obj.cunitid, index);
      this.$refs.ruleForm && this.$refs.ruleForm.clearValidate();
    },
    //主单位
    changeCunitid(e, index) {
      let rut = this.MaterialconvertList[index].find((item) => {
        return e == item.measdoccode;
      });
      let obj = this.ruleForm.detailList[index];
      obj.cunitname = rut.measdocname
      this.$set(this.ruleForm.detailList, index, obj);
    },
    //辅助物料
    changeMaterialconvert(e, index) {
      let rut = this.MaterialconvertList[index].find((item) => {
        return e == item.measdoccode;
      });
      let obj = this.ruleForm.detailList[index];
      obj.vchangerate = rut ? rut.measrate : null;
      obj.castunitname = rut ? rut.castunitname : null;
      obj.nshouldassistnum = null;
      obj.nshouldnum = null;
      obj.nassistnum = null;
      obj.nnum = null;
      this.$set(this.ruleForm.detailList, index, obj);
    },

    // 批次号
    handleChangevbatchcode(e, row) {
      let vbatchcode = row.vbatchcode;
      row.vproductbatch = vbatchcode;
    },

    // 养殖批次号
    handleChangevproductbatch(e, row) {
      console.log(e, row);
    },
    handleChangevbdef4(e, index) {
      let rut = this.StordocList.find((item) => {
        return e == item.code;
      });
      let obj = this.ruleForm.detailList[index];
      obj.vbdef4name = rut.name
      this.$set(this.ruleForm.detailList, index, obj);
    },
    handleChangevbdef5(e, index) {
      let rut = this.MaterialList.find((item) => {
        return e == item.code;
      });
      let obj = this.ruleForm.detailList[index];
      obj.vbdef5name = rut.name
      this.$set(this.ruleForm.detailList, index, obj);
    },
    handleChangevfree1(e, index) {
      let rut = this.Defdoc2List.find((item) => {
        return e == item.code;
      });
      let obj = this.ruleForm.detailList[index];
      obj.vfree1name = rut.name
      this.$set(this.ruleForm.detailList, index, obj);
    },
    //应发主数量
    handleChangenshouldnum(e, index) {
      let rut = this.ruleForm.detailList[index];
      if (!rut.nshouldnum) {
        return;
      } else {
        let nshouldnum = Number(rut.nshouldnum);
        let vchangerateList = rut.vchangerate
          ? rut.vchangerate.split("/")
          : null;
        if (vchangerateList.length) {
          rut.nshouldassistnum = nshouldnum / Number(vchangerateList[0]);
          this.$set(this.ruleForm.detailList, index, rut);
        }
      }
    },

    //应发辅数量
    handleChangenshouldassistnum(e, index) {
      let rut = this.ruleForm.detailList[index];
      if (!rut.nshouldassistnum) {
        return;
      } else {
        let nshouldassistnum = Number(rut.nshouldassistnum);
        let vchangerateList = rut.vchangerate
          ? rut.vchangerate.split("/")
          : null;
        if (vchangerateList.length) {
          rut.nshouldnum = nshouldassistnum * Number(vchangerateList[0]);
          rut.nassistnum = e;
          //会产生无限递归
          // this.handleChangenassistnum(rut,index)
          this.$set(this.ruleForm.detailList, index, rut);
        }
      }
    },

    //实发主数量
    handleChangennum(row) {
      if (!row.nnum) {
        return;
      } else {
        let nnum = (row.nnum = Number(row.nnum));
        let vchangerateList = row.vchangerate
          ? row.vchangerate.split("/")
          : null;
        if (vchangerateList.length) {
          row.nassistnum = nnum / Number(vchangerateList[0]);
        }
      }
    },

    //实发辅数量
    handleChangenassistnum(row,index) {
      if (!row.nassistnum) {
        return;
      } else {
        let nassistnum = Number(row.nassistnum);
        let vchangerateList = row.vchangerate
          ? row.vchangerate.split("/")
          : null;
        if (vchangerateList.length) {
          row.nnum = nassistnum * Number(vchangerateList[0]);
          row.nshouldassistnum = nassistnum;
          this.handleChangenshouldassistnum(nassistnum,index)
        }
      }
    },

    addMaterial() {
      let length = this.ruleForm.detailList?.length || 0;
      if (length) {
        this.$set(this.ruleForm.detailList, length, {
          vproductbatch: "",
          vbatchcode: "",
          nshouldassistnum: "",
          nshouldnum: "",
          nnum: "",
          nassistnum: "",
          vbdef1: "",
          vbdef2: "",
          vbdef4: "",
          vbdef5: "",
        });
      }
    },

    delMaterial(index) {
      let list = this.ruleForm.detailList;
      list.splice(index, 1);
      this.$set(this.ruleForm, "detailList", list);
    },
    submitFormNc() {
      console.log(this.ruleForm, "this.ruleForm");
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(255, 255, 255, 0.7)",
          });
          let formData = JSON.parse(JSON.stringify(this.ruleForm));
          delete formData.detailList;
          delete formData.measdocname;
          formData.pk_org = this.OrgOrgsList[0].code;
          formData.cprocalbodyoid = this.OrgOrgsList[0].code;
          formData.pk_group = "SSAGROUP";
          let list = [
            {
              ic_finprodin_b: this.ruleForm.detailList,
              ic_finprodin_h: formData,
            },
          ];
          console.log(list);
          NcdeadRecordApi.add_nc(list).then(async (res) => {
            if (res.success) {
              this.$message.success('操作成功');
              this.addEditFlag == 'edit' && await NcdeadRecordApi.delById(formData.id);
              this.cancel();
            } else {
              !res.success && this.errAlert(res.message)
            }
            loading.close();
          }).catch((err) => {
              this.$message.error(err);
              loading.close();
            });
        } else {
          return false;
        }
      });
    },
    //提交表单
    submitForm() {
      console.log(this.ruleForm, "this.ruleForm");
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let api = NcdeadRecordApi.add
          if (this.addEditFlag == 'add') {
            api = NcdeadRecordApi.add
          } else {
            api = NcdeadRecordApi.edit
          }
          api({
            ...this.ruleForm,
            dtlList: this.ruleForm.detailList,
            pk_org: this.OrgOrgsList[0].code,
            cprocalbodyoid: this.OrgOrgsList[0].code,
            pk_orgname: this.OrgOrgsList[0].name,
            pk_group: "SSAGROUP"
          }).then((res) => {
            let msg = res.success ? "操作成功" : "操作失败";
            this.$message[res.success ? "success" : "warning"](
              res.message || msg
            );
            res.success && this.cancel();
          })
            .catch((err) => {
              this.$message.error(err);
            });
        } else {
          return false;
        }
      });
    },
    errAlert(text) {
      this.$alert(text, '提示', {
        confirmButtonText: '确定',
        callback: action => { }
      });
    },
    //重置
    resetForm() {
      this.ruleForm = {};
      this.BatchcodeList = [];
      this.MaterialconvertList = [];
      this.$refs.ruleForm && this.$refs.ruleForm.resetFields();
    },
    //取消关闭
    cancel() {
      this.resetForm();
      this.$emit("closeDialog");
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.resetForm();
          this.cancel();
        })
        .catch((_) => { });
    },
  },
};
</script>
<style lang="scss" scoped>
.line {
  border-bottom: 1px solid #e6e6e6;
}

.icon {
  font-size: 20px;
  line-height: 29px;
  cursor: pointer;
}

::v-deep .noLabel {
  .el-form-item {
    .label {
      display: none;
    }

    .el-form-item__content {
      margin: 0;
    }
  }
}

// .demo-ruleForm{
//   display: flex;
//   .w100p{
//     width: 100%;
//   }
// }

.elrowBox {
  height: 300px;
  padding: 0 20px;
  background-color: #f5f5f5;
  overflow-y: auto;

  .elrowBoxItem {
    border: 1px #969595 dashed;
    margin-bottom: 20px;
  }
}
</style>